package com.education.platform.api.sms;

import com.alibaba.fastjson.JSON;
import com.aliyuncs.DefaultAcsClient;
import com.aliyuncs.IAcsClient;
import com.aliyuncs.dysmsapi.model.v20170525.SendSmsRequest;
import com.aliyuncs.dysmsapi.model.v20170525.SendSmsResponse;
import com.aliyuncs.profile.DefaultProfile;
import com.aliyuncs.profile.IClientProfile;
import com.education.platform.common.exception.AssertException;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;

import java.util.HashMap;
import java.util.Map;

/**
 * 阿里云短信工具
 * @author tomato
 */
public class AliyunSmsUtil {
    /**
     * 产品名称:云通信短信API产品,开发者无需替换
     */
    static final String product = "Dysmsapi";
    /**
     * 产品域名,开发者无需替换
     */
    static final String domain = "dysmsapi.aliyuncs.com";
    /**
     * 默认
     */
    static final String regionId = "cn-hangzhou";


    private static Logger LOGGER = LoggerFactory.getLogger(AliyunSmsUtil.class);


    public static void sendSms(String phoneNumber, String templateParams, SmsConfiguration smsConfiguration) {
        try {
            IClientProfile profile = DefaultProfile.getProfile(regionId, smsConfiguration.getAccessKeyId(), smsConfiguration.getAccessKeySecret());
            DefaultProfile.addEndpoint(regionId, regionId, product, domain);
            IAcsClient acsClient = new DefaultAcsClient(profile);
            SendSmsRequest request = new SendSmsRequest();
            request.setPhoneNumbers(phoneNumber);
            request.setSignName(smsConfiguration.getSignName());
            request.setTemplateCode(smsConfiguration.getTemplateCode());
            request.setTemplateParam(templateParams);
            SendSmsResponse sendSmsResponse = (SendSmsResponse) acsClient.getAcsResponse(request);
            LOGGER.info("短信发送结果：" + JSON.toJSONString(sendSmsResponse));
            if ("OK".equals(sendSmsResponse.getCode())) {
                return;
            }
        } catch (Exception e) {
            e.printStackTrace();
            LOGGER.error(" AliyunSmsUtil sendSms  error", e.getMessage());
            AssertException.throwBusinessEp("短信发送失败！");
        }
        AssertException.throwBusinessEp("短信发送失败！");
    }


}
